package com.srwl.mytx.fragment;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;

import com.alibaba.fastjson.JSONObject;
import com.github.florent37.viewanimator.ViewAnimator;
import com.google.android.material.snackbar.Snackbar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Coupon;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.CouponService;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.MoneyInputCheck;
import com.srwl.mytx.utils.NumberInputCheck;
import com.srwl.mytx.utils.PayUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.activity.CouponRecordActivity;
import com.srwl.mytx.R;
import com.srwl.redpacketui.callback.GreetingTextWatcher;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 发送一对多红包
 */
public class SendMultiplePacketDialog extends DialogFragment implements View.OnClickListener {
    private static final String TAG = "SendMultiplePacketFragm";
    private static final int FLAG_OPEN_GROUP_MEMBER = 1;
    private static final String LIVE_ROOM_ID = "LIVE_ROOM_ID";
    private static final String TOPIC_ID = "TOPIC_ID";

    private EditText mEtMoneyAmount;

    private EditText mEtMoneyCount;

    private EditText mEtGreeting;


    private Button mBtnPutMoney;

    private String mMoneyAmount;

    private int mMoneyCount = 1;

    private TextView mTvMoneyType;

    private TextView mTvMoneyTypeInfo;

    private TextView mTvAmount;

    private TextView mTvCount;

    private TextView mTvCountUnit;

    private TextView mTvAmountUnit;

    private View mMoneyLayout;

    private ProgressBar progressBar;

    private boolean mIsRandom = true; //标记是否随机金额红包

    private boolean mIsExclusive = false;

    private ImageView mIvRandomIcon;

    private String mDefaultMoneyAmount = "";

    private String mDefaultMoneyCount = "";


    private View mPopViewLayout;
    private TextView mTvRedPacketRecord;

    private TextView mTvPopMsg;
    private double mSingleLimit;
    private boolean inputCountRight;
    private boolean inputAmountRight;
    public String[] mGreetingArray;
    private int mArrayIndex;
    private InteractionListener listener;
    private String liveRoomId;
    private String topicId;
    private ImageView iv_changeGetting;

    public static SendMultiplePacketDialog newInstance(String liveRoomId, String topicId) {
        SendMultiplePacketDialog fragment = new SendMultiplePacketDialog();
        Bundle bundle = new Bundle();
        bundle.putString(LIVE_ROOM_ID, liveRoomId);
        bundle.putString(TOPIC_ID, topicId);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static SendMultiplePacketDialog newInstance() {
        SendMultiplePacketDialog fragment = new SendMultiplePacketDialog();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light_Dialog_MinWidth);
        if (getArguments() != null) {
            // mRedPacketInfo = getArguments().getParcelable(ARGS_TARGET_USER_ID);
            liveRoomId = getArguments().getString(LIVE_ROOM_ID);
            topicId = getArguments().getString(TOPIC_ID);
            if (liveRoomId == null && topicId == null) {
                throw new RuntimeException("liveRoomId和topicId 不能都为空，，，，，，，，");
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.rp_fragment_group_chat_packet, container, false);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        initViewsAndEvents(view);
        return view;
    }

    protected void initViewsAndEvents(View view) {
        // super.initViewsAndEvents(view, savedInstanceState);
        mGreetingArray = getResources().getStringArray(R.array.greetings);
        mPopViewLayout = view.findViewById(R.id.pop_layout);
        mTvPopMsg = view.findViewById(R.id.tv_popup_msg);
        mIvRandomIcon = view.findViewById(R.id.iv_random_icon);

        mMoneyLayout = view.findViewById(R.id.money_amount_layout);
        mBtnPutMoney = view.findViewById(R.id.btn_group_put_money);
        mBtnPutMoney.setOnClickListener(this);
        mTvMoneyType = view.findViewById(R.id.tv_change_type);
        mTvMoneyType.setOnClickListener(this);
        mTvMoneyTypeInfo = view.findViewById(R.id.tv_type_info);
        view.findViewById(R.id.btn_layout).setOnClickListener(this);
        iv_changeGetting = view.findViewById(R.id.iv_change_getting);
        enableButton(false);
        mTvCount = view.findViewById(R.id.tv_money_count);
        mTvCountUnit = view.findViewById(R.id.tv_count_unit);
        mTvAmount = view.findViewById(R.id.tv_total_money);
        mTvAmountUnit = view.findViewById(R.id.tv_money_unit);
        mEtMoneyAmount = view.findViewById(R.id.et_money_amount);
        mEtMoneyCount = view.findViewById(R.id.et_money_count);
        //    mTvMoneyAmount = (TextView) view.findViewById(R.id.tv_money);
        mEtGreeting = view.findViewById(R.id.et_greetings);
        mEtGreeting.setHint(mGreetingArray[0]);
        progressBar = view.findViewById(R.id.progress_bar);
        mTvRedPacketRecord = view.findViewById(R.id.tv_red_packet_Record);
        mTvRedPacketRecord.setOnClickListener(this);

        // view.findViewById(R.id.layout_members).setOnClickListener(this);
        mEtGreeting.addTextChangedListener(new GreetingTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
            }
        });
        //mTvMoneyAmount.setText(getString(R.string.rp_str_amount_zero));
        mEtMoneyAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    String moneyAmount = mEtMoneyAmount.getText().toString();
                    if (!TextUtils.isEmpty(moneyAmount)) {
                        if (moneyAmount.length() == 1 && moneyAmount.indexOf(".") == 0) {
                            setAmountRedColor();
                            if (!inputCountRight) {
                                showErrorMsg("请先输入正确的红包数量");
                            } else {
                                showErrorMsg(getString(R.string.input_money_error));
                            }
                        } else {
                            try {
                                double money = Double.valueOf(moneyAmount);
                                if (money == 0) {
                                    setAmountRedColor();
                                    if (!inputCountRight) {
                                        showErrorMsg("请先输入正确的红包数量");
                                    } else {
                                        showErrorMsg(getString(R.string.input_money_error));
                                    }
                                }
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        });

        MoneyInputCheck inputCheck = new MoneyInputCheck(getActivity(), 0.01, new MoneyInputCheck.InteractionListener() {
            @Override
            public void showErrorMessage(String message) {
//                mTvPopMsg.setText(message);
//                mPopViewLayout.setVisibility(View.VISIBLE);
                if (!inputCountRight) {
                    showErrorMsg("请先输入正确的红包数量");
                } else {
                    SendMultiplePacketDialog.this.showErrorMsg(message);
                }
                setAmountRedColor();
                inputAmountRight = false;
                mBtnPutMoney.setEnabled(false);
            }

            @Override
            public void waitInput() {
                resetAmountColorStatus();
                if (!inputCountRight) {
                    showErrorMsg("请先输入正确的红包数量");
                } else {
                    mPopViewLayout.setVisibility(View.INVISIBLE);
                }
                inputAmountRight = false;
                mBtnPutMoney.setEnabled(false);
            }

            @Override
            public void inputRight() {
                if (!inputCountRight) {
                    showErrorMsg("请先输入正确的红包数量");
                } else {
                    mPopViewLayout.setVisibility(View.INVISIBLE);
                }

                Double amount = Double.valueOf(mEtMoneyAmount.getText().toString());
                Integer count = Integer.valueOf(mEtMoneyCount.getText().toString());
                if (inputCountRight && mIsRandom && count * 0.01 > amount) {
                    showErrorMessage("单个红包金额低于0.01");
                    return;
                }
                resetAmountColorStatus();
                inputAmountRight = true;
                if (inputCountRight) {
                    mBtnPutMoney.setEnabled(true);
                }
            }
        });
        mEtMoneyAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//                        updateLimit();

                // resetAmountColorStatus();

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                inputCheck.onTextChanged(s);
            }

            @Override
            public void afterTextChanged(Editable s) {

                inputCheck.afterTextChanged(s);
            }
        });


        NumberInputCheck numberInputCheck = new NumberInputCheck(1, 500, new NumberInputCheck.InteractionListener() {
            @Override
            public void onFormatError() {
                showErrorMsg("红包数量输入格式错误");
                setCountRedColor();
                inputCountRight = false;
                mBtnPutMoney.setEnabled(false);
            }

            @Override
            public void onLessThanRange() {
                showErrorMsg("红包数量最少1个");
                setCountRedColor();
                inputCountRight = false;
                mBtnPutMoney.setEnabled(false);
            }

            @Override
            public void onMoreThanRange() {
                showErrorMsg("红包数量超过最大500个");
                setCountRedColor();
                inputCountRight = false;
                mBtnPutMoney.setEnabled(false);
            }

            @Override
            public void waitInput() {
                resetCountColorStatus();
                inputCountRight = false;
                mBtnPutMoney.setEnabled(false);
            }

            @Override
            public void inputRight() {
                mPopViewLayout.setVisibility(View.INVISIBLE);
                resetCountColorStatus();
                inputCountRight = true;

                String amountString = mEtMoneyAmount.getText().toString();
                if (mIsRandom && !TextUtils.isEmpty(amountString)) {
                    Double amount = Double.valueOf(amountString);
                    Integer count = Integer.valueOf(mEtMoneyCount.getText().toString());
                    //当红包数量符合要求，判断 红包总额是否满足每个红包至少大于1分钱
                    if (!inputAmountRight && amount >= count * 0.01) {
                        inputAmountRight = true;
                        resetAmountColorStatus();
                    } else if (amount < count * 0.01) {
                        inputAmountRight = false;
                        setAmountRedColor();
                        showErrorMsg("单个红包金额低于0.01");
                    }

                }
                if (inputAmountRight) {
                    mBtnPutMoney.setEnabled(true);
                }
            }
        });

        mEtMoneyCount.addTextChangedListener(
                new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        numberInputCheck.onTextChanged(s);
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        numberInputCheck.afterTextChanged(s);
                    }
                }

        );
    }

    private void setAmountRedColor() {
        enableButton(false);
        mEtMoneyAmount.setTextColor(ContextCompat.getColor(getActivity(), R.color.rp_money_red_light));
        mTvAmount.setTextColor(ContextCompat.getColor(getActivity(), R.color.rp_money_red_light));
        mTvAmountUnit.setTextColor(ContextCompat.getColor(getActivity(), R.color.rp_money_red_light));
    }

    private void setCountRedColor() {
        enableButton(false);
        mEtMoneyCount.setTextColor(ContextCompat.getColor(getActivity(), R.color.rp_money_red_light));
        mTvCount.setTextColor(ContextCompat.getColor(getActivity(), R.color.rp_money_red_light));
        mTvCountUnit.setTextColor(ContextCompat.getColor(getActivity(), R.color.rp_money_red_light));
    }

    private void enableButton(boolean enable) {
        mBtnPutMoney.setEnabled(enable);
    }

    private void resetAmountColorStatus() {
        mEtMoneyAmount.setTextColor(ContextCompat.getColor(getActivity(), R.color.rp_text_black));
        mTvAmount.setTextColor(ContextCompat.getColor(getActivity(), R.color.rp_text_black));
        mTvAmountUnit.setTextColor(ContextCompat.getColor(getActivity(), R.color.rp_text_black));
    }

    private void resetCountColorStatus() {

        mEtMoneyCount.setTextColor(ContextCompat.getColor(getActivity(), R.color.rp_text_black));
        mTvCount.setTextColor(ContextCompat.getColor(getActivity(), R.color.rp_text_black));
        mTvCountUnit.setTextColor(ContextCompat.getColor(getActivity(), R.color.rp_text_black));
    }

    protected int getContentViewLayoutID() {
        return R.layout.rp_fragment_group_chat_packet;
    }


    @Override
    public void onClick(View v) {

        int i = v.getId();//closeSoftKeyboard();
        if (i == R.id.btn_group_put_money) {
            if (ClickUtil.isFastClick()) return;
            mMoneyAmount = mEtMoneyAmount.getText().toString().trim();
            mMoneyCount = Integer.valueOf(mEtMoneyCount.getText().toString());
            String greeting = mEtGreeting.getText().toString().trim();
            if (verifyParams()) return;
            if (TextUtils.isEmpty(greeting)) {
                greeting = mEtGreeting.getHint().toString();
            }
            double money = Double.valueOf(mMoneyAmount);
            String finalGreeting = greeting;
            new PayUtils(money, getActivity(), new PayUtils.InteractionListener() {
                @Override
                public void onPrepareComplete(String payPassword) {

                    sendMultipleCoinCoupon(finalGreeting, money, payPassword);
                }
            });
        } else if (i == R.id.btn_layout) {
            ViewAnimator.animate(iv_changeGetting).rotation(iv_changeGetting.getRotation() + 180f).duration(300).start();
            String greeting;
            if (mArrayIndex < mGreetingArray.length) {
                greeting = mGreetingArray[mArrayIndex];
                mArrayIndex++;
            } else {
                mArrayIndex = 0;
                greeting = mGreetingArray[mArrayIndex];
                mArrayIndex++;
            }
            mEtGreeting.setText(greeting);
        } else if (i == R.id.tv_change_type) {
            changeType();

        } else if (i == R.id.tv_red_packet_Record) {
            Intent intent = new Intent(getActivity(), CouponRecordActivity.class);
            intent.putExtra(CouponRecordActivity.EXTRA_OPEN_FRAGMENT_FLAG, 2);
            startActivity(intent);

        }
    }

    private void sendMultipleCoinCoupon(String greeting, double money, String payPassword) {

        Map<String, Object> body = new HashMap<>();
        if (!TextUtils.isEmpty(payPassword)) {
            body.put("payPassword", payPassword);
        }
        Coupon coupon = new Coupon();
        coupon.setTotalCount(mMoneyCount);
        coupon.setLiveRoomId(liveRoomId);
        coupon.setTopicId(topicId);
        coupon.setGreeting(greeting);//一对多红包必须把getting 存后端
        //coupon.setCreated(new Date());
        if (mIsRandom) {
            coupon.setAmount(money);
            coupon.setType(Constant.COUPON_TYPE_MULTIPLE_RANDOM);
        } else {
            coupon.setAmount(BigDecimal.valueOf(money * mMoneyCount).setScale(2, RoundingMode.HALF_DOWN).doubleValue());
            coupon.setType(Constant.COUPON_TYPE_MULTIPLE_AVERAGE);
        }
        body.put("coupon", coupon);
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(CouponService.class)
                .sendMultipleCoupon(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "发金币红包出错：" + response.message());
                            showToast(mBtnPutMoney, getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "发金币红包出错：" + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.BALANCE_NOT_ENOUGH:
                                    showToast(mBtnPutMoney, getString(R.string.balance_not_enough));
                                    break;
                                case Constant.PAY_PASSWORD_ERROR:
                                    showToast(mBtnPutMoney, getString(R.string.pass_word_wrong));
                                    break;
                                case Constant.GET_LOCK_FAIL:
                                case Constant.FUND_COUPON_EOOR:
                                    showToast(mBtnPutMoney, getString(R.string.system_busy));
                                    break;
                            }
                            return;
                        }
                        Log.d(TAG, "发金币红包完成");
                        JSONObject data = (JSONObject) result.getData();
                        double totalBalance = data.getDouble("balance");
                        //更新本地余额
                        UserProfileManager.getInstance().setUserBalance(totalBalance);
                        //补齐红包id,因为在接收红包的时候，会用到id
                        String couponId = data.getString("couponId");
                        Date expiryDate = data.getDate("expiryDate");
                        coupon.setExpiryDate(expiryDate);
                        coupon.setId(couponId);
                        coupon.setuId(UserProfileManager.getInstance().getLoginUserInfo().getuId());
                        if (listener != null) {

                            coupon.setStatus(Constant.COUPON_STATUS_RECEIVABLE);
                            listener.onSendCouponSuccess(coupon);
                            dismiss();
                            // mBtnPutMoney.postDelayed(() -> dismiss(), 1000);
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        progressBar.setVisibility(View.GONE);
                    }
                });


    }

    private void showToast(View view, String toastContent) {
        //Snackbar.make(view, toastContent, Snackbar.LENGTH_LONG).show();
        Toast.makeText(getContext(), toastContent, Toast.LENGTH_LONG).show();
    }

    /**
     * 改变红包模式
     */
    private void changeType() {
        mTvMoneyType.setEnabled(false);
        mIsRandom = !mIsRandom;
        ObjectAnimator animator = ObjectAnimator.ofFloat(mMoneyLayout, "translationX", mMoneyLayout.getWidth(), 0.0F);
        animator.setDuration(300);
        animator.start();
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                String moneyAmount = mEtMoneyAmount.getText().toString();
                String moneyCount = mEtMoneyCount.getText().toString();
                double money;
                int count;
                String amount;
                if (!TextUtils.isEmpty(moneyAmount) && !TextUtils.isEmpty(moneyCount)) {
                    money = Double.valueOf(moneyAmount);
                    count = Integer.valueOf(moneyCount);
                    if (count == 0) {
                        count = 1;
                    }
                    if (mIsRandom) {//普通红包变随机红包
                        amount = Utils.moneyFormat(money * count);
                    } else {
                        amount = Utils.moneyFormat(money / count);
                    }
                    mEtMoneyAmount.setText(amount);
                }
                if (mIsRandom) {//普通红包变随机红包
                    mTvAmount.setText(getString(R.string.group_money_total));
                    mIvRandomIcon.setVisibility(View.VISIBLE);
                    mTvMoneyTypeInfo.setText(getString(R.string.group_rule_tips_random));
                    mTvMoneyType.setText(getString(R.string.group_change_normal));
                } else {//随机红包变普通红包
                    mTvAmount.setText(getString(R.string.group_money_every));
                    mIvRandomIcon.setVisibility(View.GONE);
                    mTvMoneyTypeInfo.setText(getString(R.string.group_rule_tips_normal));
                    mTvMoneyType.setText(getString(R.string.group_change_random));
                }
                mTvMoneyType.setEnabled(true);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    public void switchDefaultRedPacketType() {
        mEtMoneyCount.setText(mDefaultMoneyCount);
        mEtMoneyAmount.setText(mDefaultMoneyAmount);
        mIvRandomIcon.setBackgroundResource(R.drawable.rp_random_icon);
        if (mIsRandom) {//普通红包变随机红包
            mTvAmount.setText(getString(R.string.group_money_total));
            mIvRandomIcon.setVisibility(View.VISIBLE);
            mTvMoneyTypeInfo.setText(getString(R.string.group_rule_tips_random));
            mTvMoneyType.setText(getString(R.string.group_change_normal));
        } else {//随机红包变普通红包
            mTvAmount.setText(getString(R.string.group_money_every));
            mIvRandomIcon.setVisibility(View.GONE);
            mTvMoneyTypeInfo.setText(getString(R.string.group_rule_tips_normal));
            mTvMoneyType.setText(getString(R.string.group_change_random));
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }

    }

    private boolean verifyParams() {
//        if (TextUtils.isEmpty(mMoneyAmount)) {
//            showErrorMsg(getString(R.string.input_money_amount));
//            return true;
//        }
//        if (Double.valueOf(mMoneyAmount) <= 0) {
//            showErrorMsg(getString(R.string.input_money_zero));
//            return true;
//        }
//        double perMoney = Double.valueOf(mMoneyAmount) / mMoneyCount;
//        if (perMoney > mSingleLimit) {
//            String limit = String.format(getResources().getString(R.string.input_money_limited_max), getNumberLimit(mSingleLimit));
//            showErrorMsg(limit);
//            return true;
//        }
        return false;
    }

    private void showErrorMsg(String message) {
        mPopViewLayout.setVisibility(View.VISIBLE);
        mTvPopMsg.setText(message);
    }

    private void hideErrorMsg() {
        mPopViewLayout.setVisibility(View.GONE);
    }

    public void setListener(InteractionListener listener) {
        this.listener = listener;
    }

    public interface InteractionListener {

        void onSendCouponSuccess(Coupon coupon);

        void showToast(String message);
    }

}
